
import './table.scss'
import { Button, Form, Input, Popconfirm, Table } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
import axios from 'axios'
import { useParams } from 'react-router-dom';
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
// 定义一个函数 进行处理
const editableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
        
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

// 在这里发送的请求 模拟请求的发送
// (function (){
//     axios.get('/inputInfo').then((res)=>{
//       console.log(res);
//     })
// })()
const NewApp = () => {
  // 这里需要是引入的数据
  let data = [
    {
      key: '01',
      name: '用户',
      age: '18',
      address: '北京',
    }
  ]
  let newD = JSON.parse(localStorage.getItem('data')) || data
  const [dataSource, setDataSource] = useState(newD);
  let nC = Number(localStorage.getItem('count')) || 2
  const [count, setCount] = useState(nC);
  const handleDelete = (key) => {
    const newData = dataSource.filter((item) => item.key !== key);
    setDataSource(newData);
    localStorage.setItem('data',JSON.stringify(newData))
    // 这里是删除的操作
    // 再次发一个请求 进行删除操作的请求,先去配置一下
    axios.delete('/deleteinputInfo')
  };
  // Colums的初始数据 设置的是表头
  const defaultColumns = [
    {
      title: 'Name',
      dataIndex: 'name',
      width: '30%',
      editable: true,
    },
    {
      title: 'Age',
      dataIndex: 'age',
      width: '20%',
      editable: true,
    },
    {
      title: 'Address',
      dataIndex: 'address',
      width: '30%',
      editable: true,
    },
    {
      title: 'Action',
      dataIndex: 'action',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.key)}>
            <a>删除</a>
          </Popconfirm>
        ) : null,
    },
  ];
  const handleAdd = () => {
    const newData = {
      key: count,
      name: `Edward King ${count}`,
      age: '32',
      address: `London, Park Lane no. ${count}`,
    };
    setDataSource([newData,...dataSource]);
    setCount(count + 1);
    localStorage.setItem('data',JSON.stringify(dataSource))
    localStorage.setItem('count',(count+1))
  };
  const handleSave = (row) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
    // !!数据发生改变的时候执行
    localStorage.setItem('data',JSON.stringify(newData))
  };
  const components = {
    body: {
      row: EditableRow,
      cell: editableCell,
    },
  };
  // 列表头的初始数据.map
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      // 设置单元格属性
      onCell: (record) => ({
        record,
        //列数据在数据项中对应的路径，支持通过数组查询嵌套路径
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  return (
    <div style={{
      maxHeight : '90vh',
      overflow : 'auto'
    }}>
      <Button
        onClick={handleAdd}
        type="primary"
        style={{
          margin: '16px 0 2px 5px',
        }}
      >
        新增 +
      </Button>
      <Table
        //覆盖默认的table元素
        components={components}
        //表格行的类名
        rowClassName={() => 'editable-row'}
        //数据数组
        dataSource={dataSource}
        //表格列的配置描述，具体项见下表
        columns={columns}
      />
    </div>
  );
};
export default NewApp;